package com.atguigu.spzx.manager.sevice.Impl;


import cn.hutool.crypto.digest.DigestUtil;
import com.alibaba.fastjson.JSON;
import com.atguigu.spzx.common.handler.GuiguException;
import com.atguigu.spzx.manager.mapper.SysUserMapper;
import com.atguigu.spzx.manager.sevice.SysUserService;
import com.atguigu.spzx.model.dto.system.LoginDto;
import com.atguigu.spzx.model.entity.system.SysUser;
import com.atguigu.spzx.model.vo.common.ResultCodeEnum;
import com.atguigu.spzx.model.vo.system.LoginVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service
public class SysUserServiceImpl implements SysUserService {

    @Autowired
  private  SysUserMapper sysUserMapper;

    private  static  final String PREFIX = "LONGIN ";

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public LoginVo login(LoginDto loginDto) {
        String userName = loginDto.getUserName();
        String password = loginDto.getPassword();

        if (StringUtils.isEmpty(userName) || StringUtils.hasLength(password)){

            throw new GuiguException(ResultCodeEnum.USERNAME_PASSWORD_EMPTY);
        }


      SysUser sysUser = sysUserMapper.getByUsername(userName);
        if (sysUser == null){
            throw new GuiguException(ResultCodeEnum.USER_NOT_EXISTS);
        }

        if(sysUser.getPassword().equals(DigestUtil.md5(password))){
            throw  new GuiguException(ResultCodeEnum.LOGIN_ERROR);
        }

        if (sysUser.getStatus().intValue() == 0){
            throw  new GuiguException(ResultCodeEnum.ACCOUNT_STOP);

        }

        sysUser.setPassword(null);
        String jsonString = JSON.toJSONString(sysUser);

        String token = UUID.randomUUID().toString().replaceAll("-","");

        String key = PREFIX   + token ;

        stringRedisTemplate.opsForValue().set(key,jsonString,30, TimeUnit.MINUTES);

        LoginVo loginVo = new LoginVo();
        loginVo.setToken(token);
        return loginVo;
    }
}
